package com.ronghuanet.gift.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ronghuanet.gift.clients.LoginUserClient;
import com.ronghuanet.gift.domain.Employee;
import com.ronghuanet.gift.domain.LoginUser;
import com.ronghuanet.gift.domain.Tenant;
import com.ronghuanet.gift.dto.TenantEnterDto;
import com.ronghuanet.gift.exception.asserts.Assert;
import com.ronghuanet.gift.exception.code.StatusCode;
import com.ronghuanet.gift.mapper.EmployeeMapper;
import com.ronghuanet.gift.mapper.TenantMapper;
import com.ronghuanet.gift.query.TenantQuery;
import com.ronghuanet.gift.service.ITenantService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ronghuanet.gift.util.AjaxResult;
import com.ronghuanet.gift.util.PageList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaosang
 * @since 2022-10-09
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;
    @Override
    public PageList<Tenant> selectPageList(TenantQuery query) {

        Page<Tenant> page = new Page<>(query.getPage(),query.getRows());//分页条件
        List<Tenant> rows  = tenantMapper.selectPageList(page,query); //查询后，总数会放到page中，返回当前页数据
        return new PageList<>(page.getTotal(), rows);
    }


    @Autowired
    private LoginUserClient loginUserClient;

    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    @Transactional
    public AjaxResult settlement(TenantEnterDto tenantEnterDto) {
        Employee admin = tenantEnterDto.getAdmin();
        Tenant tenant = tenantEnterDto.getTenant();
        Long mealId = tenantEnterDto.getMealId();


        //1 校验
        validate(tenantEnterDto);

        //2 保存数据  店铺 店铺管理员 登陆信息  用户套餐中间表
        //2.1 保存登陆信息及用户套餐中间表并发返回loginId-->其他服务的功能（openfegin） loginUser+mealId=Map/Dto
        //方案1：谁提供服务谁写 好处：能直接用它的公共代码,坏处就是要让别人写接口---一个团队甚至一个人
        //方案2：更加接口文档自己来写  好处：没有任何耦合，坏处：有重复dto----如果两个团队分别写服务
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(admin, loginUser);
        loginUser.setType(0);//登录用户类型为管理员
        AjaxResult ajaxResult = loginUserClient.addOrUpdate(loginUser);
        if (!ajaxResult.isSuccess()){
            return AjaxResult.me().setSuccess(false).setMessage(ajaxResult.getMessage());
        }

        //2.2保存店铺管理员
        admin.setType(5);//机构管理员
        //这里登录用户返回的自增id在另一个模块，这里拿不到,所以登录用户id存到resultObj里面，
        //存的时候是Long,通过Object转换，拿出来就是Integer了
        Long loginId = Long.valueOf((ajaxResult.getResultObj().toString()));
        admin.setLoginId(loginId);
        employeeMapper.insert(admin);

        //2.3保存店铺
        tenant.setState(0);//待审核
        tenant.setAdminId(admin.getId());
        tenantMapper.insert(tenant);

        //2.4保存用户套餐中间表
        Long tenantId = tenant.getId();
        Map<String,Object> map = new HashMap<>();
        map.put("mealId",mealId);
        map.put("tenantId",tenantId);
        map.put("state", 0);//未支付
        tenantMapper.insertTenantMeal(map);

        return AjaxResult.me();
    }


    //1 异常处理-原始版
    /*
    private void validate(TenantEnterDto tenantEnterDto) {
        //1参数校验
        //1.1 null校验
        Employee admin = tenantEnterDto.getAdmin();
        Tenant tenant = tenantEnterDto.getTenant();
        Long mealId = tenantEnterDto.getMealId();
        //用户信息校验
        if(admin == null)
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        if(StringUtils.isEmpty(admin.getUsername()) || StringUtils.isEmpty(admin.getPassword()) || StringUtils.isEmpty(admin.getComfirmPassword()))
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        //两次密码比对
        if (!admin.getPassword().trim().equals(admin.getComfirmPassword().trim()))
            throw new RuntimeException("两次密码不一致");
        //租户信息校验
        if(tenant == null)
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        if (StringUtils.isEmpty(tenant.getCompanyName()) || StringUtils.isEmpty(tenant.getAddress()))
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        //套餐校验
        if(mealId == null)
            throw new RuntimeException("系统错误！请输入相关信息后再操作");


        //1.2 店铺是否存在校验
        List<Tenant> tenants = tenantMapper.selectList(new EntityWrapper<Tenant>()
                .eq("company_name", tenant.getCompanyName())
            );
        if (tenants != null && tenants.size()>0)
            throw new RuntimeException("该店铺已经存在！");
        //1.3 管理员存在校验
        List<Employee> employees = employeeMapper.selectList(new EntityWrapper<Employee>().eq("username",admin.getUsername()));
        if (employees != null && employees.size()>0)
            throw new RuntimeException("请登录，在后台添加租户提交审核！");
    }*/
    //2 自定义异常
    /*
    private void validate(TenantEnterDto tenantEnterDto) {
        //1参数校验
        //1.1 null校验
        Employee admin = tenantEnterDto.getAdmin();
        Tenant tenant = tenantEnterDto.getTenant();
        Long mealId = tenantEnterDto.getMealId();
        //用户信息校验
        if(admin == null)
            throw new BusinessException("系统错误！请输入相关信息后再操作");
        if(StringUtils.isEmpty(admin.getUsername()) || StringUtils.isEmpty(admin.getPassword()) || StringUtils.isEmpty(admin.getComfirmPassword()))
            throw new BusinessException("系统错误！请输入相关信息后再操作");
        //两次密码比对
        if (!admin.getPassword().trim().equals(admin.getComfirmPassword().trim()))
            throw new BusinessException("两次密码不一致");
        //租户信息校验
        if(tenant == null)
            throw new BusinessException("系统错误！请输入相关信息后再操作");
        if (StringUtils.isEmpty(tenant.getCompanyName()) || StringUtils.isEmpty(tenant.getAddress()))
            throw new BusinessException("系统错误！请输入相关信息后再操作");
        //套餐校验
        if(mealId == null)
            throw new BusinessException("系统错误！请输入相关信息后再操作");


        //1.2 店铺是否存在校验
        List<Tenant> tenants = tenantMapper.selectList(new EntityWrapper<Tenant>()
                .eq("company_name", tenant.getCompanyName())
        );
        if (tenants != null && tenants.size()>0)
            throw new BusinessException("该店铺已经存在！");
        //1.3 管理员存在校验
        List<Employee> employees = employeeMapper.selectList(new EntityWrapper<Employee>().eq("username",admin.getUsername()));
        if (employees != null && employees.size()>0)
            throw new BusinessException("请登录，在后台添加租户提交审核！");
    }*/

    //3 断言版
    /*
    private void validate(TenantEnterDto tenantEnterDto) {
        //1参数校验
        //1.1 null校验
        Employee admin = tenantEnterDto.getAdmin();
        Tenant tenant = tenantEnterDto.getTenant();
        Long mealId = tenantEnterDto.getMealId();
        //用户信息校验
        Assert.assertNotNull(admin,"系统错误！请输入相关信息后再操作");
        Assert.assertNotEmpty(admin.getUsername(),"系统错误！请输入相关信息后再操作");
        Assert.assertNotEmpty(admin.getPassword(),"系统错误！请输入相关信息后再操作");
        Assert.assertNotEmpty(admin.getComfirmPassword(),"系统错误！请输入相关信息后再操作");

        //两次密码比对
        Assert.assertEquals(admin.getPassword(),admin.getComfirmPassword(),"两次密码不一致");
        //租户信息校验
        Assert.assertNotNull(tenant,"系统错误！请输入相关信息后再操作");
        Assert.assertNotEmpty(tenant.getAddress(),"系统错误！请输入相关信息后再操作");
        Assert.assertNotEmpty(tenant.getCompanyName(),"系统错误！请输入相关信息后再操作");
        //套餐校验
        Assert.assertNotNull(mealId,"系统错误！请输入相关信息后再操作");

        //1.2 店铺是否存在校验
        List<Tenant> tenants = tenantMapper.selectList(new EntityWrapper<Tenant>().eq("company_name", tenant.getCompanyName()));
        Assert.assertListIsEmpty(tenants,"该店铺已经存在！");
        //1.3 管理员存在校验
        List<Employee> employees = employeeMapper.selectList(new EntityWrapper<Employee>().eq("username",admin.getUsername()));
        Assert.assertListIsEmpty(employees,"请登录，在后台添加租户提交审核！");
    }*/

    private void validate(TenantEnterDto tenantEnterDto) {
        //1参数校验
        //1.1 null校验
        Employee admin = tenantEnterDto.getAdmin();
        Tenant tenant = tenantEnterDto.getTenant();
        //两次密码比对
        Assert.assertEquals(admin.getPassword(),admin.getComfirmPassword(),"两次密码不一致");
        //1.2 店铺是否存在校验
        List<Tenant> tenants = tenantMapper.selectList(new EntityWrapper<Tenant>().eq("company_name", tenant.getCompanyName()));
        Assert.assertListIsEmpty(tenants, StatusCode.CODE_400_TENANT_EXSIT);
        //1.3 管理员存在校验
        List<Employee> employees = employeeMapper.selectList(new EntityWrapper<Employee>().eq("username",admin.getUsername()));
        Assert.assertListIsEmpty(employees, StatusCode.CODE_400_TENANT_ADMIN_EXSIT);
    }

}
